<template>
  <div class="play" :class="{ paused: paused }">
    <audio
      :src="
        'https://music.163.com/song/media/outer/url?id=' +
        currentMusic.id +
        '.mp3'
      "
      autoplay
      ref="audio"
    ></audio>

    <transition
      name="custom-classes-transition"
      enter-active-class="animate__animated animate__slideInUp"
      leave-active-class="animate__animated animate__slideOutDown"
    >
      <div
        class="play-bar"
        v-show="isShowPlayBar"
        @click="isShowPlayBar = false"
      >
        <img :src="picUrl" alt="" />
        <h5>
          {{ currentMusic.name }}
          <p>{{ currentLyrics }}</p>
        </h5>
        <div class="control" @click.stop="togglePlayState">
          <canvas ref="circle" width="50" height="50"></canvas>
          <span class="icon iconfont icon-icon_bofang" v-if="paused"></span>
          <span class="icon iconfont icon-icon_zanting" v-else></span>
        </div>
      </div>
    </transition>

    <transition
      name="custom-classes-transition"
      enter-active-class="animate__animated animate__fadeIn"
      leave-active-class="animate__animated animate__fadeOut"
    >
      <div class="play-full" v-if="!isShowPlayBar">
        <div
          class="mask"
          :style="{ background: `url(${picUrl}?param=375y667)` }"
        ></div>
        <PlayFullHeader
          @show-play-bar="isShowPlayBar = true"
          :currentMusic="currentMusic"
          :current="current"
        />
        <template>
          <transition
            mode="out-in"
            name="custom-classes-transition"
            enter-active-class="animate__animated animate__zoomInDown"
            leave-active-class="animate__animated animate__bounceOut"
          >
            <PlayFullLyric
              v-if="isShowLyric"
              @toggle-show-lyric="isShowLyric = !isShowLyric"
              :currentMusic="currentMusic"
              :currentLyricsIndex="currentLyricsIndex"
              :lyrics="lyrics"
            />
            <PlayFullChart
              v-else
              @toggle-show-lyric="isShowLyric = !isShowLyric"
              :currentMusic="currentMusic"
              :paused="paused"
              :picUrl="picUrl"
            />
          </transition>
        </template>
        <PlayFullFooter
          v-bind:currentTime="currentTime"
          v-bind:duration="duration"
          :isShowLyric="isShowLyric"
          :paused="paused"
          @play-state="togglePlayState"
          @update:currentTime="$refs.audio.currentTime = $event"
          @next-music="playNext"
          @update:songmode="songModetoggle"
        />
      </div>
    </transition>
  </div>
</template>

<script>
import PlayFullHeader from "@/components/PlayFullHeader.vue";
import PlayFullChart from "@/components/PlayFullChart.vue";
import PlayFullLyric from "@/components/PlayFullLyric.vue";
import PlayFullFooter from "@/components/PlayFullFooter.vue";
export default {
  name: "play",
  props: ["currentMusic", "currentIndex", "playlist"],
  data: function () {
    return {
      paused: null,
      duration: 0,
      currentTime: 0,
      isShowLyric: false,
      isShowPlayBar: true,
      lyrics: [],
      currentLyrics: "111",
      currentLyricsIndex: 2,
      picUrl:'',
      current:''
    };
  },
  components: {
    PlayFullHeader,
    PlayFullChart,
    PlayFullLyric,
    PlayFullFooter,
  },
  created(){
     this.axios.get('./song/detail?ids='+this.currentMusic.id)
        .then((result)=>{
          this.picUrl = result.data.songs[0].al.picUrl;
          this.current = result.data.songs[0];
        })
  },

  mounted() {
    let audio = this.$refs.audio;
    audio.addEventListener("pause", () => {
      this.paused = true;
    });
    audio.addEventListener("play", () => {
      this.paused = false;
    });

    audio.addEventListener("durationchange", () => {
      // console.log("当前歌曲时长", this.duration);
      this.duration = audio.duration;
    });

    audio.addEventListener("timeupdate", () => {
      // console.log("当前播放到", this.currentTime);
      this.currentTime = audio.currentTime;

      this.drawCircle(this.currentTime, this.duration);
    });

    audio.addEventListener("ended", () => {
      // 播放完成下一曲
      this.playNext();
    });

    this.axios("/lyric", { params: { id: this.currentMusic.id } }).then(
        (result) => {
          this.lyrics = this.paresLyric(result.data.lrc.lyric);
          setTimeout(() => {
            var _this = this;
            this.$refs.audio.ontimeupdate = function () {
              var currentTime = this.currentTime;

              var i = _this.lyrics.findIndex((element) => {
                return element.time > currentTime;
              });
              _this.currentLyricsIndex = i - 1;
            };
          });
        },
        300
      );
  },

  watch: {
    paused: function (n) {
      this.$emit("update:paused", n);
    },
    currentLyricsIndex(n) {
      if(this.lyrics[n].text=="" || !this.currentLyricsIndex)this.lyrics[n].text='111';
      this.currentLyrics = this.lyrics[n].text;
    },
    currentMusic() {
      this.axios("/lyric", { params: { id: this.currentMusic.id } }).then(
        (result) => {
          this.lyrics = this.paresLyric(result.data.lrc.lyric);
          setTimeout(() => {
            var _this = this;
            this.$refs.audio.ontimeupdate = function () {
              var currentTime = this.currentTime;

              var i = _this.lyrics.findIndex((element) => {
                return element.time > currentTime;
              });
              _this.currentLyricsIndex = i - 1;
            };
          });
        },300);
        

         this.axios.get('./song/detail?ids='+this.currentMusic.id)
        .then((result)=>{
          console.log(result.data);
          this.picUrl = result.data.songs[0].al.picUrl;
          this.current = result.data.songs[0];
        })
      
    },
  },

  methods: {
    drawCircle: function (n, total) {
      let canvas = this.$refs.circle;
      let ctx = canvas.getContext("2d");

      ctx.clearRect(0, 0, 50, 50);
      ctx.beginPath();
      ctx.strokeStyle = "rgba(0, 0, 0, 0.3)";
      ctx.arc(25, 25, 20, 0, Math.PI * 2, false); // 绘制
      ctx.stroke();
      ctx.closePath();

      ctx.beginPath();
      ctx.strokeStyle = "rgba(255, 0, 0, 0.6)";
      ctx.arc(
        25,
        25,
        19,
        Math.PI * -0.5,
        Math.PI * ((n / total) * 2 - 0.5),
        false
      ); // 绘制
      ctx.stroke();
      ctx.closePath();
    },

    togglePlayState: function () {
      let audio = this.$refs.audio;
      if (this.paused) {
        audio.play();
      } else {
        audio.pause();
      }
    },
    calculateNext: function (n) {
      // 根据当前播放模式 随机 单曲循环 顺序 顺序循环
      let nextIndex;
      if (n == "next") {
        if (this.currentIndex < this.playlist.length - 1) {
          nextIndex = this.currentIndex + 1;
        } else {
          nextIndex = 0;
        }
      } else if (n == "prev") {
        if (this.currentIndex <= 0) {
          nextIndex = this.playlist.length - 1;
        } else {
          nextIndex = this.currentIndex - 1;
        }
      }
      return nextIndex;
    },
    playNext: function (n = "next") {
      let index = this.calculateNext(n);
      this.$emit("update:music", {
        item: this.playlist[index],
        index,
      });
    },
    songModetoggle(mode) {
      if (mode == "single") {
        this.$refs.audio.loop = true;
      } else {
        this.$refs.audio.loop = false;
      }
      this.$emit("update:songmode", mode);
    },
    paresLyric(lyrics) {
      var patt = /\[\d{2}:\d{2}\.\d{2,3}\]/gi;
      var arr = lyrics
        .split("\n")
        .filter((e) => e)
        .map((str) => {
          var time = str.match(patt)[0].replace(/(\[|\])/gi, "");
          var timeArr = time.split(":");
          time = Number(timeArr[0]) * 60 + Number(timeArr[1]);
          var text = str.replace(patt, "");
          return { time, text };
        });
      return arr;
    },
  },
};
</script>

<style scoped lang="less">
audio {
  position: fixed;
  bottom: 50px;
  height: 30px;
}
.play {
  &.paused {
    .play-bar {
      img {
        animation-play-state: paused;
      }
    }
  }
}
.play-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  background: white;
  display: flex;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.15);
  height: 7vh;
  img {
    width: 5vh;
    height: 5vh;
    margin: 5px 7px;
    border-radius: 50%;
    animation: playing 6s linear infinite;
    box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.15);
  }
  h5 {
    flex: 1;
    font-size: 12px;
    margin-top: 5px;
    p {
      color: rgb(102, 101, 101);
    }
  }
  .control {
    position: relative;
    display: grid;
    place-content: center;
    canvas {
      width: 36px;
      height: 36px;
      margin: 5px 0;
    }
    span.icon {
      position: absolute;
      width: 100%;
      height: 90%;
      top: 0;
      left: 0;
      display: grid;
      place-content: center;
      font-size: 12px;
      margin-top: 3px;
    }
  }
}
.play-full {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index:10;
  background: linear-gradient(
    to right,
    rgb(56, 56, 56),
    rgb(95, 95, 95),
    rgb(56, 56, 56)
  );
  .mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: -1;
    filter: blur(20px);
    background-position: center !important;
    background-size: cover !important;
    opacity: 0.5;
  }
}

@keyframes playing {
  form {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>